"""
客户端控制面板UI - 现代化版本
"""
import tkinter as tk
from tkinter import ttk, messagebox
from core import config
from .styles import COLORS, FONTS, SPACING, create_card_frame, create_modern_button, create_status_indicator


class ClientPanel:
    """客户端控制面板"""
    
    def __init__(self, room_id: str, central_ac):
        self.room_id = room_id
        self.central_ac = central_ac
        
        self.window = tk.Toplevel()
        self.window.title(f"空调控制 - 房间 {room_id}")
        self.window.geometry("550x800")
        self.window.resizable(True, True)  # 允许调整大小
        self.window.minsize(550, 800)  # 设置最小尺寸
        self.window.configure(bg=COLORS['background'])
        
        # 添加全屏支持（F11切换）
        self.is_fullscreen = False
        self.window.bind('<F11>', self._toggle_fullscreen)
        self.window.bind('<Escape>', self._exit_fullscreen)
        
        self._setup_ui()
        self._update_display()
        
        # 定期更新显示
        self.window.after(1000, self._auto_update)
    
    def _setup_ui(self):
        """设置UI界面"""
        # 标题栏
        header_frame = tk.Frame(
            self.window,
            bg=COLORS['primary'],
            height=80
        )
        header_frame.pack(fill=tk.X)
        header_frame.pack_propagate(False)
        
        title_label = tk.Label(
            header_frame,
            text=f"房间 {self.room_id}",
            font=FONTS['title'],
            bg=COLORS['primary'],
            fg='white'
        )
        title_label.pack(pady=(SPACING['lg'], SPACING['xs']))
        
        subtitle_label = tk.Label(
            header_frame,
            text="智能空调控制系统",
            font=FONTS['body'],
            bg=COLORS['primary'],
            fg='#E0E7FF'
        )
        subtitle_label.pack()
        
        # 主内容区
        content_frame = tk.Frame(
            self.window,
            bg=COLORS['background'],
            padx=SPACING['lg'],
            pady=SPACING['lg']
        )
        content_frame.pack(fill=tk.BOTH, expand=True)
        
        # 状态信息卡片
        self._create_status_section(content_frame)
        
        # 控制面板卡片
        self._create_control_section(content_frame)
        
        # 操作按钮
        self._create_action_buttons(content_frame)
    
    def _create_status_section(self, parent):
        """创建状态显示区域"""
        shadow_frame, card = create_card_frame(parent)
        shadow_frame.pack(fill=tk.X, pady=(0, SPACING['lg']))
        card.config(padx=SPACING['lg'], pady=SPACING['lg'])
        
        # 状态标题
        status_header = tk.Frame(card, bg=COLORS['card_bg'])
        status_header.pack(fill=tk.X, pady=(0, SPACING['md']))
        
        tk.Label(
            status_header,
            text="运行状态",
            font=FONTS['heading'],
            fg=COLORS['text_primary'],
            bg=COLORS['card_bg']
        ).pack(side=tk.LEFT)
        
        # 状态指示器
        self.status_indicator_frame, self.status_dot, self.status_text = create_status_indicator(
            status_header,
            "关闭",
            'off'
        )
        self.status_indicator_frame.pack(side=tk.RIGHT)
        self.status_indicator_frame.config(bg=COLORS['card_bg'])
        
        # 温度显示区
        temp_container = tk.Frame(card, bg=COLORS['card_bg'])
        temp_container.pack(fill=tk.X, pady=SPACING['md'])
        
        # 当前温度
        current_temp_frame = tk.Frame(temp_container, bg=COLORS['card_bg'])
        current_temp_frame.pack(side=tk.LEFT, expand=True, fill=tk.X)
        
        tk.Label(
            current_temp_frame,
            text="当前温度",
            font=FONTS['small'],
            fg=COLORS['text_secondary'],
            bg=COLORS['card_bg']
        ).pack(anchor=tk.W)
        
        self.current_temp_label = tk.Label(
            current_temp_frame,
            text="--°C",
            font=('Segoe UI', 32, 'bold'),
            fg=COLORS['temp_normal'],
            bg=COLORS['card_bg']
        )
        self.current_temp_label.pack(anchor=tk.W)
        
        # 分隔线
        separator = tk.Frame(temp_container, width=2, bg=COLORS['border'])
        separator.pack(side=tk.LEFT, fill=tk.Y, padx=SPACING['lg'])
        
        # 目标温度
        target_temp_frame = tk.Frame(temp_container, bg=COLORS['card_bg'])
        target_temp_frame.pack(side=tk.LEFT, expand=True, fill=tk.X)
        
        tk.Label(
            target_temp_frame,
            text="目标温度",
            font=FONTS['small'],
            fg=COLORS['text_secondary'],
            bg=COLORS['card_bg']
        ).pack(anchor=tk.W)
        
        self.target_display_label = tk.Label(
            target_temp_frame,
            text="--°C",
            font=('Segoe UI', 32, 'bold'),
            fg=COLORS['primary'],
            bg=COLORS['card_bg']
        )
        self.target_display_label.pack(anchor=tk.W)
        
        # 费用显示
        cost_frame = tk.Frame(card, bg=COLORS['background'], height=60)
        cost_frame.pack(fill=tk.X, pady=(SPACING['md'], 0))
        cost_frame.pack_propagate(False)
        
        # 费用卡片内容
        cost_inner = tk.Frame(cost_frame, bg=COLORS['primary'])
        cost_inner.pack(fill=tk.BOTH, expand=True, padx=1, pady=1)
        
        cost_content = tk.Frame(cost_inner, bg='#EEF2FF', padx=SPACING['md'], pady=SPACING['md'])
        cost_content.pack(fill=tk.BOTH, expand=True)
        
        tk.Label(
            cost_content,
            text="当前费用",
            font=FONTS['body'],
            fg=COLORS['text_secondary'],
            bg='#EEF2FF'
        ).pack(side=tk.LEFT)
        
        self.cost_label = tk.Label(
            cost_content,
            text="¥0.00",
            font=FONTS['medium_display'],
            fg=COLORS['secondary'],
            bg='#EEF2FF'
        )
        self.cost_label.pack(side=tk.RIGHT)
    
    def _create_control_section(self, parent):
        """创建控制面板区域"""
        shadow_frame, card = create_card_frame(parent)
        shadow_frame.pack(fill=tk.X, pady=(0, SPACING['lg']))
        card.config(padx=SPACING['lg'], pady=SPACING['lg'])
        
        # 控制标题
        tk.Label(
            card,
            text="控制设置",
            font=FONTS['heading'],
            fg=COLORS['text_primary'],
            bg=COLORS['card_bg']
        ).pack(anchor=tk.W, pady=(0, SPACING['md']))
        
        # 模式选择
        mode_container = tk.Frame(card, bg=COLORS['card_bg'])
        mode_container.pack(fill=tk.X, pady=(0, SPACING['lg']))
        
        tk.Label(
            mode_container,
            text="运行模式",
            font=FONTS['body_bold'],
            fg=COLORS['text_primary'],
            bg=COLORS['card_bg']
        ).pack(anchor=tk.W, pady=(0, SPACING['sm']))
        
        mode_buttons_frame = tk.Frame(mode_container, bg=COLORS['card_bg'])
        mode_buttons_frame.pack(fill=tk.X)
        
        self.mode_var = tk.StringVar(value=config.MODE_COOLING)
        
        # 自定义单选按钮样式
        self.cooling_btn = tk.Radiobutton(
            mode_buttons_frame,
            text="制冷",
            variable=self.mode_var,
            value=config.MODE_COOLING,
            font=FONTS['body_bold'],
            bg=COLORS['card_bg'],
            fg=COLORS['primary'],
            selectcolor=COLORS['card_bg'],
            activebackground=COLORS['card_bg'],
            relief=tk.FLAT,
            padx=SPACING['lg'],
            pady=SPACING['sm'],
            command=self._on_mode_change
        )
        self.cooling_btn.pack(side=tk.LEFT, expand=True, fill=tk.X, padx=(0, SPACING['xs']))
        
        self.heating_btn = tk.Radiobutton(
            mode_buttons_frame,
            text="制热",
            variable=self.mode_var,
            value=config.MODE_HEATING,
            font=FONTS['body_bold'],
            bg=COLORS['card_bg'],
            fg=COLORS['danger'],
            selectcolor=COLORS['card_bg'],
            activebackground=COLORS['card_bg'],
            relief=tk.FLAT,
            padx=SPACING['lg'],
            pady=SPACING['sm'],
            command=self._on_mode_change
        )
        self.heating_btn.pack(side=tk.LEFT, expand=True, fill=tk.X, padx=(SPACING['xs'], 0))
        
        # 温度设置
        temp_container = tk.Frame(card, bg=COLORS['card_bg'])
        temp_container.pack(fill=tk.X, pady=(0, SPACING['lg']))
        
        temp_header = tk.Frame(temp_container, bg=COLORS['card_bg'])
        temp_header.pack(fill=tk.X, pady=(0, SPACING['sm']))
        
        tk.Label(
            temp_header,
            text="设定温度",
            font=FONTS['body_bold'],
            fg=COLORS['text_primary'],
            bg=COLORS['card_bg']
        ).pack(side=tk.LEFT)
        
        self.target_temp_label = tk.Label(
            temp_header,
            text="25°C",
            font=FONTS['heading'],
            fg=COLORS['primary'],
            bg=COLORS['card_bg']
        )
        self.target_temp_label.pack(side=tk.RIGHT)
        
        # 温度滑块
        self.target_temp_var = tk.IntVar(value=25)
        
        # 使用标准tk.Scale（更稳定）
        self.target_temp_scale = tk.Scale(
            temp_container,
            from_=18,
            to=30,
            orient=tk.HORIZONTAL,
            variable=self.target_temp_var,
            command=self._on_temp_change,
            bg=COLORS['card_bg'],
            fg=COLORS['primary'],
            troughcolor=COLORS['border'],
            highlightthickness=0,
            bd=0,
            relief=tk.FLAT,
            font=FONTS['body'],
            length=300,
            width=15,
            sliderlength=25
        )
        self.target_temp_scale.pack(fill=tk.X, pady=SPACING['sm'])
        
        # 温度范围标签
        temp_range_frame = tk.Frame(temp_container, bg=COLORS['card_bg'])
        temp_range_frame.pack(fill=tk.X, pady=(SPACING['xs'], 0))
        
        tk.Label(
            temp_range_frame,
            text="18°C",
            font=FONTS['small'],
            fg=COLORS['text_secondary'],
            bg=COLORS['card_bg']
        ).pack(side=tk.LEFT)
        
        tk.Label(
            temp_range_frame,
            text="30°C",
            font=FONTS['small'],
            fg=COLORS['text_secondary'],
            bg=COLORS['card_bg']
        ).pack(side=tk.RIGHT)
        
        # 风速选择
        wind_container = tk.Frame(card, bg=COLORS['card_bg'])
        wind_container.pack(fill=tk.X)
        
        tk.Label(
            wind_container,
            text="风速档位",
            font=FONTS['body_bold'],
            fg=COLORS['text_primary'],
            bg=COLORS['card_bg']
        ).pack(anchor=tk.W, pady=(0, SPACING['sm']))
        
        wind_buttons_frame = tk.Frame(wind_container, bg=COLORS['card_bg'])
        wind_buttons_frame.pack(fill=tk.X)
        
        self.wind_speed_var = tk.StringVar(value=config.WIND_SPEED_MEDIUM)
        
        wind_options = [
            ("低风", config.WIND_SPEED_LOW),
            ("中风", config.WIND_SPEED_MEDIUM),
            ("高风", config.WIND_SPEED_HIGH)
        ]
        
        for i, (text, value) in enumerate(wind_options):
            btn = tk.Radiobutton(
                wind_buttons_frame,
                text=text,
                variable=self.wind_speed_var,
                value=value,
                font=FONTS['body'],
                bg=COLORS['card_bg'],
                fg=COLORS['text_primary'],
                selectcolor=COLORS['card_bg'],
                activebackground=COLORS['card_bg'],
                relief=tk.FLAT,
                padx=SPACING['md'],
                pady=SPACING['sm'],
                command=self._on_wind_speed_change
            )
            padx_left = 0 if i == 0 else SPACING['xs']
            padx_right = 0 if i == len(wind_options) - 1 else SPACING['xs']
            btn.pack(side=tk.LEFT, expand=True, fill=tk.X, padx=(padx_left, padx_right))
    
    def _create_action_buttons(self, parent):
        """创建操作按钮"""
        button_frame = tk.Frame(parent, bg=COLORS['background'])
        button_frame.pack(fill=tk.X)
        
        # 开关机按钮（统一按钮，根据状态切换）
        self.power_button = create_modern_button(
            button_frame,
            "开机",
            self._toggle_power,
            style='success',
            height=2
        )
        self.power_button.pack(fill=tk.X)
    
    def _on_temp_change(self, value):
        """温度变化回调"""
        temp = int(float(value))
        self.target_temp_var.set(temp)
        self.target_temp_label.config(text=f"{temp}°C")
        
        # 如果空调已开机，立即更新温度设置
        room_state = self.central_ac.get_room_state(self.room_id)
        if room_state and room_state['is_on']:
            self.central_ac.handle_request(
                self.room_id,
                temp,
                self.wind_speed_var.get(),
                self.mode_var.get()
            )
    
    def _on_wind_speed_change(self):
        """风速变化回调"""
        # 如果空调已开机，立即更新风速设置
        room_state = self.central_ac.get_room_state(self.room_id)
        if room_state and room_state['is_on']:
            self.central_ac.handle_request(
                self.room_id,
                self.target_temp_var.get(),
                self.wind_speed_var.get(),
                self.mode_var.get()
            )
    
    def _on_mode_change(self):
        """模式变化回调"""
        # 如果空调已开机，立即更新模式设置
        room_state = self.central_ac.get_room_state(self.room_id)
        if room_state and room_state['is_on']:
            self.central_ac.handle_request(
                self.room_id,
                self.target_temp_var.get(),
                self.wind_speed_var.get(),
                self.mode_var.get()
            )
    
    def _toggle_power(self):
        """开关机按钮回调"""
        room_state = self.central_ac.get_room_state(self.room_id)
        
        if room_state and room_state['is_on']:
            # 当前开机，执行关机
            result = self.central_ac.turn_off(self.room_id)
        else:
            # 当前关机，执行开机
            target_temp = self.target_temp_var.get()
            wind_speed = self.wind_speed_var.get()
            mode = self.mode_var.get()
            
            result = self.central_ac.handle_request(
                self.room_id,
                target_temp,
                wind_speed,
                mode
            )
        
        # 不显示弹窗，直接更新显示
        self._update_display()
    
    def _update_display(self):
        """更新显示"""
        room_state = self.central_ac.get_room_state(self.room_id)
        
        if room_state:
            # 更新按钮文本和样式
            if room_state['is_on']:
                self.power_button.config(
                    text="关机",
                    bg=COLORS['danger'],
                    activebackground=COLORS['danger_dark']
                )
                # 更新悬停效果
                self.power_button.bind('<Enter>', lambda e: self.power_button.config(bg=COLORS['danger_dark']))
                self.power_button.bind('<Leave>', lambda e: self.power_button.config(bg=COLORS['danger']))
            else:
                self.power_button.config(
                    text="开机",
                    bg=COLORS['success'],
                    activebackground=COLORS['success_dark']
                )
                # 更新悬停效果
                self.power_button.bind('<Enter>', lambda e: self.power_button.config(bg=COLORS['success_dark']))
                self.power_button.bind('<Leave>', lambda e: self.power_button.config(bg=COLORS['success']))
            
            # 更新当前温度
            current_temp = room_state['current_temp']
            self.current_temp_label.config(text=f"{current_temp:.1f}°C")
            
            # 根据温度调整颜色
            if current_temp < 20:
                temp_color = COLORS['temp_cold']
            elif current_temp > 26:
                temp_color = COLORS['temp_hot']
            else:
                temp_color = COLORS['temp_normal']
            self.current_temp_label.config(fg=temp_color)
            
            # 更新目标温度显示
            if room_state['target_temp']:
                self.target_display_label.config(text=f"{room_state['target_temp']:.0f}°C")
            else:
                self.target_display_label.config(text="--°C")
            
            # 更新状态指示器
            if room_state['is_on']:
                if room_state['is_serving']:
                    status_text = "服务中"
                    status = 'serving'
                    color = COLORS['secondary']
                elif room_state['is_waiting']:
                    status_text = "等待中"
                    status = 'waiting'
                    color = COLORS['warning']
                else:
                    status_text = "待机中"
                    status = 'standby'
                    color = COLORS['info']
            else:
                status_text = "已关闭"
                status = 'off'
                color = COLORS['text_disabled']
            
            self.status_text.config(text=status_text, fg=color)
            self.status_dot.delete('all')
            self.status_dot.create_oval(2, 2, 10, 10, fill=color, outline='')
            
            # 更新费用
            self.cost_label.config(text=f"¥{room_state['total_cost']:.2f}")
    
    def _auto_update(self):
        """自动更新"""
        if self.window.winfo_exists():
            self._update_display()
            self.window.after(1000, self._auto_update)
    
    def _toggle_fullscreen(self, event=None):
        """切换全屏模式"""
        self.is_fullscreen = not self.is_fullscreen
        self.window.attributes('-fullscreen', self.is_fullscreen)
    
    def _exit_fullscreen(self, event=None):
        """退出全屏"""
        self.is_fullscreen = False
        self.window.attributes('-fullscreen', False)
    
    def show(self):
        """显示窗口"""
        self.window.mainloop()
